import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.io.*;

/**
 * 聊天室
 */
public class ChatServer {
    private List<Socket> sockets = new ArrayList<Socket>();

    public ChatServer() throws IOException {
        this.init();
    }

    public void init() throws IOException {
        ServerSocket ss = new ServerSocket(8081);
        while (true) {
            Socket socket = ss.accept();
            sockets.add(socket);
            String ip = socket.getInetAddress().getHostAddress();
            System.out.println("进来一个" + ip);
            Thread thread = new Thread(new ServerRunner(sockets, socket));
            thread.start();
        }
    }

    public static void main(String[] args) {
        try {
            new ChatServer();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

class ServerRunner implements Runnable {
    private List<Socket> sockets;
    private Socket currentSocket;

    public ServerRunner(List<Socket> sockets, Socket currentSocket) {
        this.sockets = sockets;
        this.currentSocket = currentSocket;
    }

    @Override
    public void run() {
        String ip = currentSocket.getInetAddress().getHostAddress();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(currentSocket.getInputStream()));
            String str = null;
            while ((str = br.readLine()) != null) {
                System.out.println(ip + "说" + str);
                for (Socket temp : sockets) {
                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(temp.getOutputStream()));
                    pw.println(str);
                    pw.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}